package com.rock.upms.svc.upms.service.impl;

import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.rock.common.base.BaseConstants;
import com.rock.common.util.ByteUtil;
import com.rock.common.util.RedisUtil;
import com.rock.common.util.RockJsonUtil;
import com.rock.common.util.SerializeUtil;
import com.rock.common.util.StringUtil;
import com.rock.upms.api.model.service.IUpmsPersonService;
import com.rock.upms.api.model.service.IUpmsThirdBindService;
import com.rock.upms.api.upms.service.IAuthService;
import com.rock.upms.model.UpmsPerson;
import com.rock.upms.model.UpmsPersonExample;
import com.rock.upms.model.UpmsThirdBind;
import com.rock.upms.model.UpmsThirdBindExample;
import com.rock.upms.model.UpmsThirdBindExample.Criteria;
import com.rock.upms.model.dto.UpmsRedisKey;
import com.rock.upms.model.dto.UserDto;

@Repository
@Service
public class AuthService implements IAuthService {

	private static final Logger log = LoggerFactory.getLogger(AuthService.class);
	@Autowired
	private IUpmsPersonService upmsPersonService;
	@Autowired
	private IUpmsThirdBindService upmsThirdBindService;

	/**
	 * 验证ptoken是否有效<br>
	 * 1 从redis中获取该token对应的user信息 <br>
	 * 2 若user不为空则有效，否则无效
	 */
	@Override
	public Boolean isValidPToken(String primarytoken) {
		log.trace("===>isValidPToken入参，primarytoken：" + primarytoken);
		if (StringUtil.isBlank(primarytoken)) {
			return false;
		}
		byte[] userByte = RedisUtil.hget(ByteUtil.getByteKey(UpmsRedisKey.PRIMARY_TOKEN_KEY_PREFIX, primarytoken), UpmsRedisKey.HASH_KEY_USER.getBytes());
		if (userByte != null) {
			UserDto user = (UserDto) SerializeUtil.deserialize(userByte);
			if (user != null) {
				log.trace("===>user:" + RockJsonUtil.toJson(user));
				return true;
			}
		}
		log.trace("===>isValidPToken出参，user:null" );
		return false;
	}

	@Override
	public String getPTokenByThirdId(String thirdid, String thirdComcode) {
		UpmsThirdBindExample bindExample = new UpmsThirdBindExample();
		Criteria criteria = bindExample.createCriteria();
		criteria.andThirdIdEqualTo(thirdid);
		criteria.andThirdComcodeEqualTo(thirdComcode);
		criteria.andIsDeletedEqualTo(BaseConstants.NOT_DELETED);
		UpmsThirdBind bindInfo = upmsThirdBindService.selectFirstByExample(bindExample);
		if (bindInfo != null) {
			return this.getPTokenByMobilephone(bindInfo.getMobilephone());
		} else {
			return null;
		}
	}

	@Override
	public String getPTokenByUsercode(String usercode) {
		byte[] ptokenByte = RedisUtil.get(ByteUtil.getByteKey(UpmsRedisKey.USERCODE_KEY_PREFIX, usercode));
		if (ptokenByte != null) {
			String ptoken = (String) SerializeUtil.deserialize(ptokenByte);// 获取token
			// 验证token
			if (isValidPToken(ptoken)) {
				return ptoken;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@Override
	public String getPTokenByMobilephone(String mobilephone) {
		UpmsPersonExample example = new UpmsPersonExample();
		com.rock.upms.model.UpmsPersonExample.Criteria criteria = example.createCriteria();
		criteria.andMobilephoneEqualTo(mobilephone);
		criteria.andIsDeletedEqualTo(BaseConstants.NOT_DELETED);
		UpmsPerson upmsPerson = upmsPersonService.selectFirstByExample(example);
		if (upmsPerson != null) {
			return getPTokenByUsercode(upmsPerson.getUsercode());
		} else {
			return null;
		}
	}

	@Override
	public String getPTokenByCaid(String caid) {
		UpmsPersonExample example = new UpmsPersonExample();
		com.rock.upms.model.UpmsPersonExample.Criteria criteria = example.createCriteria();
		criteria.andCaidEqualTo(caid);
		criteria.andIsDeletedEqualTo(BaseConstants.NOT_DELETED);
		UpmsPerson upmsPerson = upmsPersonService.selectFirstByExample(example);
		if (upmsPerson != null) {
			return getPTokenByUsercode(upmsPerson.getUsercode());
		} else {
			return null;
		}
	}

	@Override
	public boolean isValidRole(String ptoken, String role) {
		byte[] rolesByte = RedisUtil.hget(ByteUtil.getByteKey(UpmsRedisKey.PRIMARY_TOKEN_KEY_PREFIX, ptoken), UpmsRedisKey.HASH_KEY_ROLES.getBytes());
		if (rolesByte != null) {
			Set<String> roles = (Set<String>) SerializeUtil.deserialize(rolesByte);
			log.trace("===>roles:" + RockJsonUtil.toJson(roles));
			return roles.contains(role);
		} else {
			log.trace("===>roles:null");
			return false;
		}
	}

	@Override
	public boolean isValidPermission(String ptoken, String permission) {
		byte[] permissionByte = RedisUtil.hget(ByteUtil.getByteKey(UpmsRedisKey.PRIMARY_TOKEN_KEY_PREFIX, ptoken), UpmsRedisKey.HASH_KEY_PERMISSIONS.getBytes());
		if (permissionByte != null) {
			Set<String> permissions = (Set<String>) SerializeUtil.deserialize(permissionByte);
			log.trace("===>permissions:" + RockJsonUtil.toJson(permissions));
			return permissions.contains(permission);
		} else {
			log.trace("===>permissions:null");
			return false;
		}
	}
}
